import React from 'react';
import { Table, Input, Button, Divider, message, Select, Row, Col, DatePicker, Modal } from 'antd';
import { $http } from 'containers/config/https';
import { $loadTemplate } from '../lodop/Common/Print.js';
import { Keup, ArraySome, dayFormat } from 'tools/index';
import store from 'store';
import moment from 'moment';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import WasteAndReclaimed from '../Cashier/charges/component/WasteAndReclaimed';
import PatPayModal from '../Cashier/charges/component/PatPayModal'
import CommonPagination from 'components/pagination/index';
import 'assets/css/system.css';

const Option = Select.Option;
export default class OPChargeException extends React.Component {
    constructor(props) {
        super(props);
        this.updateMoney = this.updateMoney.bind(this);
        this.updatePay = this.updatePay.bind(this);
        this.MakeMoney = this.MakeMoney.bind(this);
        this.state = {
            //输入的参数
            chargeUserID: '',
            patNo: '',
            cardTypeID: "",
            cardNo: '',
            stDate: "",
            endDate: "",
            //下拉框数组
            cardTypeData: [],
            userList: [],
            // 主菜单列表数据
            data: [],
            columns: [],
            // 抽屉显示
            visible: false,
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true,
            total: 0,
            page: 1,
            pageSize: 10,
            //visibility:hidden/visible
            visiData: [],
            modalShow: false,
            modalShowPay: false,
            recordinvID: '', //收款记录发票记录服务的ID
            invType: '',//收款记录发票记录服务的类型
            parkRecordDrinfo: '', // 退费的负付款记录
            chargeRecodeId: '', // 交款记录id
            sflag: '', // 类型 退费收费
            patID: '',
            compleRecordIDinfo: '',  // //compleRecordIDinfo
            invIDinfo: '',  // //invIDinfo
            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识

        }
    }

    ///生命周期 数据异步请求，请求成功之后setState
    componentDidMount() {
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.setState({ chargeUserID: sessionInfo.userID }, () => {
            console.log("HHHH", this.state.chargeUserID);
            this.tableList();
            this.cardTypeList();
            this.handleUserQuery();
        })
        this.setState({
            showLoading: false,
            chargeUserID: JSON.parse(window.sessionStorage.userData).userID
        }
        )
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    //render 自定义项目名称
    listAdd = (i, j, languageCode) => {
        let { columns } = this.state
        columns.splice(i, j,
            {
                title: languageCode === 'CN' ? "操作" : 'Operation',
                key: 'op',
                align: "center",
                width: '70px',
                render: (value, record, index) => {
                    let { visiData } = this.state;
                    let visi = visiData.includes(record.recordID) ? 'hidden' : 'visible';
                    const obj = {
                        children: (
                            <span>
                                <span className='span' onClick={this.handleFinish.bind(this, record)} >{languageCode === 'CN' ? "完成" : 'Complete'}</span>
                                <Divider type="vertical" />
                                <span className='span' onClick={this.handleBack.bind(this, record)} style={{ "visibility": visi }}>{languageCode === 'CN' ? "撤销" : 'Cancel'}</span>
                            </span>
                        ),
                        props: {},
                    };
                    obj.props.rowSpan = record.num;
                    //const totalObj={}
                    return (obj);
                }
            },
        )
    }

    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }

    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["OPChargeException"],
                "compontName": "OPChargeException",
                "type": "C"
            }]
        }
        console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    let { languageCode } = this.state
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }
                    if (languageCode === "EN") {
                        resC.map((item, i) => {
                            item.title = item.enDescripts
                        })
                    }

                    if (languageCode === "CN") {
                        resC.map((item, i) => {
                            item.title = item.descripts
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                        this.listAdd(filterArr.length + 1, 0, languageCode);
                    })
                }
            }
        })
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    appPageChange = (page, pageSize) => {
        this.setState({
            page: page,
            pageSize: pageSize,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    // 条数改变的回调
    apponShowSizeChange = (current, size) => {
        this.setState({
            page: current,
            pageSize: size,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    //卡类型
    cardTypeList = () => {
        var data = {
            params: [{
                hospID: JSON.parse(window.sessionStorage.userData).hospID, //医院id 
            }]
        }

        $http.post('urlS', this, {
            code: "01040059",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let cardDeffault = res.cardType.filter((item) => {
                        return item.defaultFlag === 'Y';
                    })
                    this.setState({
                        cardTypeID: cardDeffault[0].id, // 默认卡
                        cardTypeData: res.cardType,  // 用户数据
                    });
                }
            }
        });
    }

    // 人员下拉框
    handleUserQuery = () => {
        let data = {}
        data = {
            params: [{
                hospID: JSON.parse(window.sessionStorage.userData).hospID,
                locTypeCode: "C",
            }]
        }
        $http.post('urlS', this, {
            code: '05210023',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.user) {
                    let tempList = []
                    for (var i = 0; i < res.user.length; i++) {
                        tempList.push(<Option key={res.user[i].id} alias={res.user[i].descriptsSPCode}>{res.user[i].descripts}</Option>)
                    }
                    this.setState({
                        userList: tempList,
                        userData: res.user
                    }
                        , () => {
                            let defaultSelect = this.state.userData.filter((item) => {
                                return item.id === this.state.chargeUserID
                            })
                            if (defaultSelect.length < 1) {
                                var chargeUserIDch = ""
                                //if(this.state.userData.length>0){var chargeUserIDch=this.state.userData[0].id+""}else{var chargeUserIDch=""}
                                this.setState({
                                    chargeUserID: chargeUserIDch,
                                }, () => {
                                    this.handleQuery();
                                }
                                )
                            } else { this.handleQuery(); }
                        }

                    )
                }
            }
        })
    }

    /***双向绑定***/
    onChangeChargeUserID = (value) => {
        if (value) { } else { value = "" }
        this.setState({
            chargeUserID: value
        })
    }

    onChangePatNo = (e) => {
        this.setState({
            patNo: e.target.value
        });
    }

    onChangeCardTypeID = (value) => {
        this.setState({
            cardTypeID: value
        });
    }

    onChangeCardNo = (e) => {
        this.setState({
            cardNo: e.target.value
        });
    }

    onChangeStDate = (value) => {
        if (value) { } else { value = "" }
        this.setState({
            stDate: value
        });
    }

    onChangeEndDate = (value) => {
        if (value) { } else { value = "" }
        this.setState({
            endDate: value
        });
    }

    // 退费弹框
    updateMoney = () => {
        this.handleCancel()  // 关闭弹框
        Keup.ModalMessage(3, this, this.state.languageCode === "CN" ? '成功!' : 'success!', this.state.languageCode === "CN" ? '自动关闭' : 'Automatically shut down', 'destroy', this.state.languageCode === "CN" ? '确定' : 'define', 'success');
        // 刷新列表数据*/
        this.handleQuery();
    }

    // 收费弹框
    updatePay = () => {
        this.handleCancel()  // 关闭弹框
        Keup.ModalMessage(3, this, this.state.languageCode === "CN" ? '成功!' : 'success!', this.state.languageCode === "CN" ? '自动关闭' : 'Automatically shut down', 'destroy', this.state.languageCode === "CN" ? '确定' : 'define', 'success');
        // 刷新列表数据*/
        this.handleQuery();
    }

    // 弹框关闭
    handleCancel = () => {
        // let { sflag, chargeRecodeId } = this.state
        this.setState({
            modalShow: false,
            modalShowPay: false,
        });
        // if (sflag === 0) {
        //     var data = {
        //         params: [{
        //             "recordIDinfo": chargeRecodeId, //付款记录串
        //             "hisTradeNum": "",   //his交易流水
        //             "userID": JSON.parse(window.sessionStorage.userData).userID || '', //操作人
        //             "ip": React.$getSessionData('ipConfig')?.ipv4 || '', //ip
        //         }]
        //     }


        //     $http.post('urlADS', this, {
        //         code: "05210010",
        //         data: data,
        //         success: function (res) {
        //             let errorCode = res.errorCode;
        //             if (errorCode === '0') {

        //             }
        //         }
        //     });
        // }
    }

    /***增删改查111***/
    // 查询
    handleQuery = () => {
        let { chargeUserID, patNo, cardTypeID, cardNo, stDate, endDate, cardTypeData } = this.state;
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            params: [{
                hospID: sessionInfo.hospID,
                chargeUserID: chargeUserID,
                patNo: patNo,
                cardTypeID: cardTypeID,
                cardNo: cardNo,
                stDate: stDate ? moment(stDate).format(dayFormat) : '',
                endDate: endDate ? moment(endDate).format(dayFormat) : ''
            }]
        }
        let cardTypeFilter = cardTypeData.filter(function (item) {
            return item.id == cardTypeID;
        })
        let zeroLength = cardTypeFilter[0] ? cardTypeFilter[0].cardLength : 0
        if (zeroLength && zeroLength != '' && parseFloat(zeroLength) != 0) {
            data = {
                params: [{
                    hospID: sessionInfo.hospID,
                    chargeUserID: chargeUserID,
                    patNo: patNo,
                    cardTypeID: cardTypeID,
                    cardNo: cardNo != '' ? ArraySome.addPreZero(cardNo, zeroLength) : '',
                    stDate: stDate ? moment(stDate).format(dayFormat) : '',
                    endDate: endDate ? moment(endDate).format(dayFormat) : ''
                }]
            }
            if (cardNo && cardNo != '') {
                this.setState({
                    cardNo: ArraySome.addPreZero(cardNo, zeroLength),
                })
            }
            if (patNo && patNo != '') {
                this.setState({
                    patNo: ArraySome.addPreZero(patNo, zeroLength),
                })
            }
        }
        $http.post('urlS', this, {
            code: '05210022',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.recordInfo) {
                    let visiData = []
                    for (var i = 0; i < res.recordInfo.length; i++) {
                        res.recordInfo[i].key = i;
                        if (res.recordInfo[i].sflag === 1) { visiData.push(res.recordInfo[i].recordID) }
                    }
                    this.setState({ data: res.recordInfo, total: res.recordInfo.length, loading: false, visiData: visiData }, () => {
                    }
                    )
                } else {
                    this.setState({
                        data: [],
                        visiData: [],
                        total: 0,
                    })
                }
            }
        })
    }

    ////完成
    handleFinish = (record) => {
        let insuPayID = record.insuPayID
        let insuStatus = record.insuStatus
        if ((insuPayID != "") && (insuStatus != 'N')) {
            Keup.ModalMessage(10, "医保结算失败，不能确认完成！！！", '自动关闭', 'destroy', '确定', 'error')
            return
        }
        if (record.sflag == 1) {
            this.setState({
                recordinvID: record.oldRecordIDStr || '',
                invType: record.invFlag || '',
                parkRecordDrinfo: record.minusRecordIDStr || '',
                chargeRecodeId: record.recordIDStr || '',
                sflag: record.sflag,
            }, () => {
                this.setState({
                    modalShowPay: true,
                })
            })
        }
        if (record.sflag == 0) {
            this.setState({
                chargeRecodeId: record.recordIDStr || '',
                sflag: record.sflag,
                patID: record.patID,
            }, () => {
                this.setState({
                    modalShow: true,
                })
            })
        }
    }

    //撤销
    handleBack = async (record) => {
        let insuPayID = record.insuPayID
        let insuStatus = record.insuStatus
        if ((insuPayID != '') && (insuStatus === 'N')) {
            let openModal = Modal.info({
                title: "正在进行医保退费,请稍等...",
                content: <Spin size="large" />,
                okText: "",
                onOk() { },
            });
            //医保费用先进行医保退费
            ///医保退费
            let dllInputdata = {
                "params": [{
                    "userID": JSON.parse(window.sessionStorage.userData).userID,
                    "insuPayID": insuPayID,
                    "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                    "patID": record.patID || '',  //病人id
                }],
                "code": "05210046"
            }
            let YBPatDivdata = await INSUYBUtil.insuYBAHSYB("InsuOPRefund", dllInputdata);
            let res = JSON.parse(YBPatDivdata);
            openModal.destroy(); // 弹框等待提示
            if (res.errorCode != '0') {
                //医保退费失败
                Keup.ModalMessage(10, this, res.errorMessage, '自动关闭', 'destroy', '确定', 'error')
                return
            }

        }
        let data = {}
        data = {
            params: [{
                hisTradeNum: record.tradNum
            }]
        }
        $http.post('urlADS', this, {
            code: "05210010",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('撤销成功');
                    // 刷新列表数据*/
                    this.handleQuery();
                }
            },
            error: function (error) {
                message.error('撤销失败：' + error);
            }
        })
    }

    onRefPatPay = (ref) => {
        this.childfPatPay = ref
    }

    //收银确认按钮
    payButtonOk = () => {
        if (!this.childfPatPay.chargingConfirError()) {
            return false
        }
        this.childfPatPay.chargingConfir() //确认收费
    }

    MakeMoney(res) {
        this.handleQuery()  // 查询
        this.handleCancel()  // 关闭弹框
        Keup.ModalMessage(3, this, this.state.languageCode === "CN" ? '支付成功!' : 'Payment successful!', this.state.languageCode === "CN" ? '自动关闭' : 'Automatically shut down', 'destroy', this.state.languageCode === "CN" ? '确定' : 'define', 'success');

        this.setState({
            compleRecordIDinfo: res.compleRecordIDinfo,
            invIDinfo: res.invIDinfo
        }, () => {
            this.print()  // 打印
        })
    }

    // 打印
    print = () => {
        var data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id 
                "groupID": JSON.parse(window.sessionStorage.userData).groupID,  //角色id
                "printType": "O",
                "printTemplateCode": "",
                "recordIDStr": this.state.compleRecordIDinfo || '',
                "invIDStr": this.state.invIDinfo || '',
            }]
        }
        $http.post('urlADS', this, {
            code: "05100153",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let dataArr = res.data
                    let template = res.template
                    dataArr.map((item, i) => {
                        $loadTemplate(template[i], item.toString());
                    })
                }
            }
        });
    }

    render() {
        let { language } = this.state

        return (
            <div>
                <div>
                    {/*写成标签对可以但不要分离太远*/}
                    <div className="table-operations">
                        <Row style={{ minHeight: '60px', padding: '0 24px 12px 24px' }}>
                            <Select allowClear style={{ width: '150px', margin: '12px 15px 0 0' }} placeholder={this.state.languageCode === "CN" ? "请选择卡类型" : 'Please select Card Type'} value={this.state.cardTypeID} onChange={(event) => { this.onChangeCardTypeID(event) }}  >
                                <Option value=''>{this.state.languageCode === "CN" ? "请选择" : 'Please Select'}</Option>
                                {this.state.cardTypeData.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                            </Select>
                            <Input placeholder={language.OPChargeExceptioncardID && language.OPChargeExceptioncardID.message} style={{ width: '260px', margin: '12px 15px 0 0' }} value={this.state.cardNo} onChange={this.onChangeCardNo} onPressEnter={this.handleQuery} />
                            {language.OPChargeExceptionpatientInformation && language.OPChargeExceptionpatientInformation.descripts}： <Input placeholder={language.OPChargeExceptionpatientInformation && language.OPChargeExceptionpatientInformation.message} style={{ width: '260px', margin: '12px 15px 0 0' }} value={this.state.patNo} onChange={this.onChangePatNo} onPressEnter={this.handleQuery} />
                            {language.OPChargeExceptiontollCollector && language.OPChargeExceptiontollCollector.descripts}：<Select
                                showSearch
                                allowClear
                                placeholder={language.OPChargeExceptiontollCollector && language.OPChargeExceptiontollCollector.message}
                                optionFilterProp="children"
                                style={{ width: '150px', margin: '12px 15px 0 0' }}
                                value={this.state.chargeUserID}
                                onChange={this.onChangeChargeUserID}
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >{this.state.userList}</Select>

                            {language.OPChargeExceptionstartDate && language.OPChargeExceptionstartDate.descripts}: < DatePicker style={{ width: '150px', margin: '12px 15px 0 0' }} format="YYYY-MM-DD" onChange={this.onChangeStDate} /*value={this.state.stDate}*/ />
                            {language.OPChargeExceptionendDate && language.OPChargeExceptionendDate.descripts}：< DatePicker style={{ width: '150px', margin: '12px 15px 0 0' }} format="YYYY-MM-DD" onChange={this.onChangeEndDate} /*value={this.state.endDate}*/ />


                            <Button onClick={this.handleQuery} style={{ margin: '12px 15px 0 0', background: 'rgba(255,255,255,1)' }} >{language.OPChargeExceptionquery && language.OPChargeExceptionquery.descripts}</Button>
                        </Row>
                    </div>
                    <div style={{ background: '#f0f2f5', height: '10px' }}></div>
                    <Row>
                        <Col span={24} style={{ padding: 24 }}  >
                            {/* <Table
                                style={{ height: store.getState().tableHeight.y + 45 + 'px', marginTop: '15px' }}
                                dataSource={this.state.data}
                                columns={this.columns}
                                bordered    //让属table表格清晰显示
                                pagination={false}
                            //scroll={{ y: 2000 }}
                            /> */}
                            <Table
                                style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
                                dataSource={this.state.data}
                                columns={this.state.columns}
                                className='TableA'
                                //rowClassName="editable-row"
                                pagination={false}
                                scroll={{ x: 900, y: store.getState().tableHeight.y }}
                                bordered
                                loading={this.state.loading}
                            />
                            <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                                onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.data}
                                onChange={this.appPageChange} />
                            <ColumnAuthoritysModel
                                clientWidth='900px'
                                compontName='OPChargeException'
                                configType="C"
                                onRef={this.onColumnRef}
                                reloadData={this.tableList}
                            />

                        </Col>
                    </Row>

                </div>
                {/* 退费弹框 */}
                <Modal
                    visible={this.state.modalShowPay}
                    title={this.state.languageCode === "CN" ? '作废重收' : 'Discard And Recycling'}
                    width='900px'
                    className='modalPay'
                    closable={false}
                    keyboard={false}
                    footer={null}
                >
                    <WasteAndReclaimed key={this.state.chargeRecodeId} updateMoney={this.updateMoney} recordinvID={this.state.recordinvID} invType={this.state.invType} parkRecordDrinfo={this.state.parkRecordDrinfo} chargeRecodeId={this.state.chargeRecodeId} ></WasteAndReclaimed>
                </Modal>

                {/* 收费弹框 */}
                <Modal
                    visible={this.state.modalShow}
                    title={this.state.languageCode === "CN" ? '收银' : 'Cash Register'}
                    width='900px'
                    className='modalPay'
                    onCancel={this.handleCancel}
                    footer={null}
                    maskClosable={false}
                >
                    <PatPayModal patID={this.state.patID} onRef={this.onRefPatPay} chargeRecodeId={this.state.chargeRecodeId} key={this.state.chargeRecodeId} MakeMoney={this.MakeMoney} handthis={this} />
                    {/* <CashRegister key={this.state.chargeRecodeId} updatePay={this.updatePay} chargeRecodeId={this.state.chargeRecodeId} ></CashRegister> */}
                    <div style={{ textAlign: 'right', margin: '10px 0' }}>
                        <Button onClick={this.handleCancel} style={{ marginRight: '20px' }}>{this.state.languageCode === "CN" ? '取消' : 'Cancel'}</Button>
                        <Input type="primary" value={this.state.languageCode === "CN" ? "确定" : 'define'} readOnly="readOnly" onClick={this.payButtonOk} style={{ textAlign: 'center', backgroundColor: '#1999db', width: '60px', color: '#fff', cursor: 'pointer' }} onPressEnter={this.payButtonOk} />
                    </div>
                </Modal>
            </div>
        )
    }
}